package com.jubaozan.service.platform.decorator;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jubaozan.c3.framework.utils.ResultHolder;
import com.jubaozan.dao.youme.domain.Store;
import com.jubaozan.dao.youme.domain.StoreGoods;
import com.jubaozan.dao.youme.service.StoreGoodsService;
import com.jubaozan.dao.youme.service.StoreService;
import com.jubaozan.feign.supplier.audit.SupplierNwtFeignService;
import com.jubaozan.feign.supplier.audit.vo.Category;
import com.jubaozan.feign.supplier.audit.vo.GoodsSku;
import com.jubaozan.feign.supplier.audit.vo.ScGoods;
import com.jubaozan.feign.supplier.audit.vo.Supplier;
import com.jubaozan.feign.supplier.goods.SupplierGoodsFeignService;
import com.jubaozan.feign.supplier.goods.vo.GoodsVO;
import com.jubaozan.feign.supplier.goods.vo.SupplierNetworkInfo;
import com.jubaozan.service.platform.vo.ScGoodsVO;
import com.jubaozan.feign.platform.vo.StoreVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Auther: chenjingui
 * @Date: 2020/9/21 16:29
 * @Description:
 */
@Slf4j
@Component
public class StoreDecorator {
    @Autowired
    private StoreService storeService;
    @Autowired
    private StoreGoodsService storeGoodsService;
    @Autowired
    private SupplierNwtFeignService supplierNwtFeignService;
    @Autowired
    private SupplierGoodsFeignService supplierGoodsFeignService;

   public IPage getStoreList(Page<Store> page,String title){
       QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("status",1);
      if(title!=null){
          queryWrapper.like("title",title);
      }
       IPage<Store> storePage = storeService.page(page, queryWrapper);
       if(!StringUtils.isEmpty(storePage)){
           return  storePage;
       }
      return  null;
   }
    public StoreVO queryStoreDetails(Long id){
        Store store = storeService.getById(id);
        if(store!=null){
            StoreVO storeVO = new StoreVO();
            BeanUtils.copyProperties(store,storeVO);
            return storeVO;
        }
            return  null;
    }
    //oneCategoryId supplierId  goodsName是非必须参数 可能为空 也可能不为空
    public ResultHolder<IPage<ScGoodsVO>> getGoods(Long oneCategoryId, Long supplierId, String goodsName, Integer pageNo,
                                                  Integer pageSize, Long storeId){
        ResultHolder<Page<ScGoods>> resultHolder = supplierNwtFeignService.platformGoods(oneCategoryId,supplierId,goodsName,pageNo,pageSize);
        //供应商市场审核且上架的商品
        IPage<ScGoods> supplierGoodsList = resultHolder.getBody();
        String supplierName = (supplierId != null ? supplierName(supplierId) : null);
        String oneCategoryName = (oneCategoryId != null ? oneCategoryName(oneCategoryId) : null);
        if(storeId == null || supplierGoodsList.getRecords().size() == 0){
            return ResultHolder.success(supplierGoodsList.convert(scGoods -> convertScGoodsToVO(scGoods, false, supplierId, supplierName, oneCategoryId, oneCategoryName)));
        } else {
            //如果选中了个体平台 storeId！=null;
            LambdaQueryWrapper<StoreGoods> queryWrapper = new QueryWrapper<StoreGoods>().lambda()
                    .eq(StoreGoods::getStoreId, storeId)
                    .in(StoreGoods::getGoodsId, supplierGoodsList.getRecords().stream().map(ScGoods::getId).collect(Collectors.toList()));
            //查询已经被该个体平台选择到的商品
            Map<Long, StoreGoods> map = storeGoodsService.list(queryWrapper).stream().collect(Collectors.toMap(StoreGoods::getGoodsId, sg -> sg));
            return ResultHolder.success(supplierGoodsList.convert(scGoods -> convertScGoodsToVO(scGoods, map.containsKey(scGoods.getId()), supplierId, supplierName, oneCategoryId, oneCategoryName)));
        }
    }

    private ScGoodsVO convertScGoodsToVO(ScGoods supplierGood, Boolean selected, Long supplierId, String supplierName, Long oneCategoryId, String oneCategoryName){
        ScGoodsVO scGoodsVO =new ScGoodsVO();
        scGoodsVO.setScGoods(supplierGood);
        scGoodsVO.setSelect(selected);
        scGoodsVO.setGoodsSkuList(this.getGoodsSkus(supplierGood.getId()));
        scGoodsVO.setSupplierName(supplierId != null ? supplierName : this.supplierName(supplierGood.getSupplierId()));
        scGoodsVO.setOneCategoryName(oneCategoryId!=null ? oneCategoryName : this.oneCategoryName(supplierGood.getOneCategoryId()));
        return scGoodsVO;
    }

    //将商品选入个体平台
    @Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
   public boolean saveGoodsToStore(String username,Long storeId,List<Long> goodsId) {
       QueryWrapper<StoreGoods> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("store_id", storeId);
        List<StoreGoods> storeGoodsList = storeGoodsService.list(queryWrapper);
      if(!CollectionUtils.isEmpty(storeGoodsList)){
          storeGoodsService.remove(queryWrapper);
      }
           //重新插入关系
           List<StoreGoods> newStoreGoodsList = new ArrayList<>();
           for (int i = 0; i < goodsId.size(); i++) {
               StoreGoods storeGoods = new StoreGoods();
               storeGoods.setStoreId(storeId);
               storeGoods.setGoodsId(goodsId.get(i));
              storeGoods.setCreateBy(username);
               storeGoods.setStatus(1);
               newStoreGoodsList.add(storeGoods);
           }
           return storeGoodsService.saveBatch(newStoreGoodsList);

   }

    public ResultHolder<IPage<ScGoodsVO>> getSelectGoods(Long oneCategoryId, Long supplierId, String goodsName, Integer
            pageNo, Integer pageSize, Long storeId) {
        //如果选中了个体平台 storeId！=null;
        QueryWrapper<StoreGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id",storeId);
        String supplierName = (supplierId != null ? supplierName(supplierId) : null);
        String oneCategoryName = (oneCategoryId!=null ? oneCategoryName(oneCategoryId) : null);
        IPage<StoreGoods> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNo);
        //查询已经被该商家选择到的商品
        IPage<StoreGoods> storeSelectGoodsList = storeGoodsService.page(page, queryWrapper);
        if(storeSelectGoodsList.getRecords().size()>0){
            Map<Long, GoodsVO> map = supplierGoodsFeignService.listGoodsByIds(storeSelectGoodsList.getRecords().stream().map(StoreGoods::getGoodsId).collect(Collectors.toList())).unpack()
                    .stream().collect(Collectors.toMap(GoodsVO::getId, g -> g));
            return ResultHolder.success(storeSelectGoodsList.convert(storeGoods -> convertGoodsVOToScGoodsVO(storeGoods, map, supplierId, supplierName, oneCategoryId, oneCategoryName)));
        }
        return  ResultHolder.success(storeSelectGoodsList.convert(storeGoods -> convertGoodsVOToScGoodsVO(storeGoods, null, supplierId, supplierName, oneCategoryId, oneCategoryName)));
    }
    private ScGoodsVO convertGoodsVOToScGoodsVO(StoreGoods storeGoods, Map<Long, GoodsVO> mapGoodsVO, Long supplierId, String supplierName, Long oneCategoryId, String oneCategoryName){
        ScGoodsVO scGoodsVO =new ScGoodsVO();
        Optional.ofNullable(mapGoodsVO.get(storeGoods.getGoodsId())).ifPresent(goodsVO -> {
            ScGoods scGoods = new ScGoods();
            BeanUtils.copyProperties(goodsVO, scGoods);
            scGoodsVO.setScGoods(scGoods);
            scGoodsVO.setSupplierName(supplierId != null ? supplierName : this.supplierName(goodsVO.getSupplierId()));
            scGoodsVO.setOneCategoryName(oneCategoryId!=null ? oneCategoryName : this.oneCategoryName(goodsVO.getCategoryId()));
            goodsVO.getResources().stream().filter(goodsResourcesVO -> goodsResourcesVO.getSeq() == 1 && "1".equals(goodsResourcesVO.getType())).findFirst()
                    .ifPresent(goodsResourcesVO -> scGoods.setImageLink(goodsResourcesVO.getUrl()));
        });
        scGoodsVO.setSelect(true);
        scGoodsVO.setGoodsSkuList(this.getGoodsSkus(storeGoods.getGoodsId()));
        return scGoodsVO;

    }
  //替换供应商名称的方法
    public  String supplierName(Long supplierId) {
        if (supplierId != null) {
            ResultHolder<List<Supplier>> listResultHolder = supplierNwtFeignService.querySuppliers(supplierId);
            if (listResultHolder.getBody() != null) {
                if (!StringUtils.isEmpty(listResultHolder.getBody().get(0).getName())) {
                    return listResultHolder.getBody().get(0).getName();
                }

            } else {
                ResultHolder<List<SupplierNetworkInfo>> listResultNetworkInfo = supplierNwtFeignService.queryNetworkInfoList(supplierId);
                if (listResultNetworkInfo.getBody() != null) {
                    if (!StringUtils.isEmpty(listResultNetworkInfo.getBody().get(0).getShopName())) {
                        return listResultNetworkInfo.getBody().get(0).getShopName();
                    }
                }


            }
            return "供应商名字不详";
        }
        return "供应商名字不详";
    }
    //一级商品分组替换名字
    public  String oneCategoryName( Long oneCategoryId){
        if(oneCategoryId!=null){
            ResultHolder<List<Category>> listResultHolder = supplierNwtFeignService.queryCategorys(oneCategoryId);
            if( listResultHolder.getBody()!=null){
                return listResultHolder.getBody().get(0).getName();
            }
            return  "分类名字不详";
        }
        return null;
    }
    public List<GoodsSku> getGoodsSkus(Long goodsId){
        if(goodsId!=null){
            ResultHolder<List<GoodsSku>> goodsSkus= supplierNwtFeignService.getGoodsSku(goodsId);
            if(!CollectionUtils.isEmpty(goodsSkus.getBody())){
                return goodsSkus.getBody();
            }
            return null;
        }
        return null;
    }
}
